package sorttest;

import java.util.Arrays;

/**
 * @author small瑞
 * 归并排序
 */
public class MergeTry {
    public static void main(String[] args) {
        int tr[] = new int[100];
        for(int i = 0 ; i < 100 ; i++){
            tr[i] = (int)(Math.random()*100);
        }
        System.out.println(Arrays.toString(merger(tr)));
    }
    static int[] merger(int[] arr) {
        int mid;
        if (arr.length < 2) {
            return arr;
        } else {
            mid = arr.length / 2;
        }
        return merge(merger(Arrays.copyOfRange(arr, 0, mid)), merger(Arrays.copyOfRange(arr, mid, arr.length)));

    }
    static int[] merge(int[] left , int[] right){
        int[] ans = new int [left.length+right.length];
        for(int cur = 0 , l = 0 , r = 0 ,len = ans.length;cur<len;cur++){
            if(l >= left.length){
                ans[cur] = right[r++];
            }
            else if( r >= right.length){
                ans[cur] = left[l++];
            }
            else if( left[l] >right[r]){
                ans[cur] = right[r++];
            }
            else{
                ans[cur] = left[l++];
            }
        }
        return ans;
    }
}

